package com.dabai.qrtools.ui;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dabai.qrtools.R;
import com.dabai.qrtools.adapter.QrListAdapter;
import com.dabai.qrtools.bean.QrInfo;
import com.dabai.qrtools.dialog.MdcDialog;
import com.dabai.qrtools.other.ImageUtils;
import com.dabai.qrtools.other.MainUtils;
import com.dabai.qrtools.qrcode.QRCodeUtils;
import com.dabai.qrtools.utils.DabaiUtils;
import com.dabai.qrtools.utils.DisplayUtils;
import com.dabai.qrtools.utils.FileUtils;
import com.dabai.qrtools.utils.SAFUtils;
import com.dabai.qrtools.utils.ThemeUtils;
import com.dabai.qrtools.utils.UriUtils;
import com.dabai.qrtools.utils.ViewUtils;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputLayout;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.ArrayList;
import java.util.Objects;
import java.util.Random;


public class BatchGenerateActivity extends AppCompatActivity {

    private Context context;
    private MaterialToolbar mToolbar;
    private TextInputLayout mTil1;
    private Button mButton1;
    private SwipeRecyclerView mRecyclerview;
    private QrListAdapter qrListAdapter;
    private ArrayList<QrInfo> qrInfoArrayList;
    private CheckBox mCheckbox1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_batch_generate);
        initViews();


        context = this;

        ThemeUtils.setAutoUiModeStatusBar(this, this);
        setSupportActionBar(mToolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        initAdapter();

        initListenerEvent();


    }


    // 创建菜单：
    SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {

            SwipeMenuItem item0 = new SwipeMenuItem(context)
                    .setHeight(MATCH_PARENT)
                    .setWidth(DisplayUtils.dip2px(context, 70))
                    .setImage(R.drawable.ic_outline_fullscreen_24)
                    .setBackgroundColor(Color.parseColor("#4CAF50"));
            leftMenu.addMenuItem(item0); // 在Item左侧添加一个菜单。

            SwipeMenuItem item1 = new SwipeMenuItem(context)
                    .setHeight(MATCH_PARENT)
                    .setWidth(DisplayUtils.dip2px(context, 70))
                    .setImage(R.drawable.ic_outline_save_24)
                    .setBackgroundColor(Color.parseColor("#3F51B5"));
            rightMenu.addMenuItem(item1); // 在Item左侧添加一个菜单。


            SwipeMenuItem item2 = new SwipeMenuItem(context)
                    .setHeight(MATCH_PARENT)
                    .setWidth(DisplayUtils.dip2px(context, 70))
                    .setImage(R.drawable.ic_outline_delete_24)
                    .setBackgroundColor(Color.parseColor("#F44336"));
            rightMenu.addMenuItem(item2); // 在Item左侧添加一个菜单。


        }
    };

    // 菜单点击监听。
    @SuppressLint("NotifyDataSetChanged")
    OnItemMenuClickListener mItemMenuClickListener = (menuBridge, position) -> {
        // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
        menuBridge.closeMenu();

        // 左侧还是右侧菜单：
        int direction = menuBridge.getDirection();
        // 菜单在Item中的Position：
        int menuPosition = menuBridge.getPosition();

        //判断是 左侧菜单
        if (direction == SwipeRecyclerView.LEFT_DIRECTION) {
            QrInfo qrInfo = qrInfoArrayList.get(position);

            if (menuPosition == 0) {
                ImageUtils.showBigImage(context, qrInfo.getQr());
            }

        }

        //判断是 右侧菜单
        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
            QrInfo qrInfo = qrInfoArrayList.get(position);

            if (menuPosition == 0) {
                QRCodeUtils.saveQrImageToDCIM(context, qrInfo.getContent());
            }
            if (menuPosition == 1) {
                qrInfoArrayList.remove(position);
                qrListAdapter.notifyDataSetChanged();
            }
        }
    };


    private void initAdapter() {

        qrInfoArrayList = new ArrayList<>();
        //准备适配器
        qrListAdapter = new QrListAdapter(qrInfoArrayList);
        //设置适配器
        qrListAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn);

        mRecyclerview.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        mRecyclerview.setLayoutManager(new LinearLayoutManager(this));

        // 创建侧滑 和 设置侧滑监听器  一定要在 adapter设置之前!!!
        mRecyclerview.setSwipeMenuCreator(mSwipeMenuCreator);
        mRecyclerview.setOnItemMenuClickListener(mItemMenuClickListener);

        mRecyclerview.setAdapter(qrListAdapter);


        qrListAdapter.setOnItemClickListener((adapter, view, position) -> {
            QrInfo qrInfo = (QrInfo) adapter.getData().get(position);
            ImageUtils.showBigImage(context, qrInfo.getQr());

        });

        qrListAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            QrInfo qrInfo = (QrInfo) adapter.getData().get(position);

            new MaterialAlertDialogBuilder(context)
                    .setItems(new String[]{"复制文本内容", "自由复制文本"}, (dialog, which) -> {
                        if (which == 0) {
                            DabaiUtils.copyText(context, qrInfo.getContent());
                        }
                        if (which == 1) {
                            MainUtils.toFreeCopy(context, qrInfo.getContent());
                        }
                    }).show().getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);

            return true;
        });

    }

    @SuppressLint("NotifyDataSetChanged")
    private void initListenerEvent() {

        mButton1.setOnClickListener(v -> {
            String text = ViewUtils.getTextInputLayoutText(mTil1);
            if (text.isEmpty()) {
                return;
            }

            Bitmap bitmap = QRCodeUtils.createSimpleQrCodeBitmap(context,text, 1000);
            if (bitmap == null) {
                qrInfoArrayList.add(new QrInfo("此项数据异常，可能是超出了二维码容量", QRCodeUtils.createSimpleQrCodeBitmap(context,"null")));
            } else {
                qrInfoArrayList.add(new QrInfo(text, bitmap));
            }

            qrListAdapter.notifyDataSetChanged();

            if (mCheckbox1.isChecked()){
                ViewUtils.setTextInputLayoutText(mTil1,"");
            }

        });

        //解决滑动冲突
        ViewUtils.FixScrollViewConflict(mTil1.getEditText());

    }

    private void initViews() {
        mToolbar = findViewById(R.id.toolBar);
        mTil1 = findViewById(R.id.til1);
        mButton1 = findViewById(R.id.button1);
        mRecyclerview = findViewById(R.id.recyclerView);
        mCheckbox1 = findViewById(R.id.checkBox1);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.batch_generate, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
        if (itemId == R.id.textImport) {

            if (DabaiUtils.isFunctionFirstOpen(context, "textImport")) {
                DabaiUtils.showDialog(context, "请选择一个文本文件，程序会根据换行符来分段生成。");
                return true;
            }

            SAFUtils.openFile(this, "text/*", 601);

            return true;
        }
        if (itemId == R.id.saveAll) {

            if (qrInfoArrayList.size() <= 0) {
                DabaiUtils.showToast(context, "保存失败");
                return true;
            }

            MdcDialog.showConfirmDialog(context, "提示", "是否保存" + qrInfoArrayList.size() + "张二维码到图库?"
                    , new MdcDialog.OnConfirmDialogButtonListener() {
                        @Override
                        public void confirm() {
                            for (QrInfo qrInfo : qrInfoArrayList) {
                                FileUtils.saveBitmapToDCIM(context, qrInfo.getQr(), "QRTools", "QRTools_batch_" + new Random().nextInt(100000));
                            }
                            DabaiUtils.showToast(context, "保存完成");

                        }

                        @Override
                        public void cancel() {

                        }
                    }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);


            return true;
        }
        if (itemId == R.id.clear) {

            if (qrInfoArrayList.size() <= 0) {
                return true;
            }

            MdcDialog.showConfirmDialog(context, "提示", "是否删除列表中的" + qrInfoArrayList.size() + "条二维码记录?"
                    , new MdcDialog.OnConfirmDialogButtonListener() {
                        @SuppressLint("NotifyDataSetChanged")
                        @Override
                        public void confirm() {

                            qrInfoArrayList.clear();
                            qrListAdapter.notifyDataSetChanged();

                        }

                        @Override
                        public void cancel() {

                        }
                    }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);

            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 601) {
                if (data != null) {

                    new Thread(() -> {

                        UriUtils uriUtils = new UriUtils(context, data.getData());
                        String socText = uriUtils.readText();

                        String[] texts = socText.split("\n");

                        if (texts.length > 300) {
                            runOnUiThread(() -> DabaiUtils.showDialog(context, "性能限制，禁止生成300张以上"));
                            return;
                        }

                        for (String text : texts) {
                            if (text.isEmpty()) {
                                return;
                            }
                            Bitmap bitmap = QRCodeUtils.createSimpleQrCodeBitmap(context,text, 1000);
                            if (bitmap == null) {
                                qrInfoArrayList.add(new QrInfo("此项数据异常，可能是超出了二维码容量", QRCodeUtils.createSimpleQrCodeBitmap(context,"null")));
                            } else {
                                qrInfoArrayList.add(new QrInfo(text, bitmap));
                            }
                            runOnUiThread(() -> qrListAdapter.notifyDataSetChanged());

                        }
                    }).start();

                }
            }
        }

    }

}